package com.tsfyun.common.base.support;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.tsfyun.common.base.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Objects;

/**
 * @Description: jackson对json的字符串参数去前后空格及特殊符号
 * @since Created in 2020/3/27 16:22
 */
@Slf4j
public class StringDeserializer extends JsonDeserializer<String> {

    public static final StringDeserializer instance = new StringDeserializer();

    @Override
    public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        String val = jsonParser.getText();
        try {
            if(Objects.nonNull(val)) {
                val = StringUtils.null2EmptyWithTrim(val);
                val = StringUtils.removeSpecialSymbol(val);
            }
        } catch (Exception e) {
            //如果执行出错则返回原值不影响参数的绑定
            log.info("json字符串参数:{}",val);
            log.error("json字符串参数去前后空格异常",e);
        }
        return val;
    }
}
